package us.luosl.hadoop.mr.io;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;

/**
 * Created by luosl on 2018/9/3.
 */
public class JsonCount {
    public static class JsonWordCountMapper extends Mapper<Object, MapWritable, Text, IntWritable>{

        private IntWritable one = new IntWritable(1);
        private Text text = new Text();

        @Override
        protected void map(Object key, MapWritable value, Context context) throws IOException, InterruptedException {
            for(Writable k:value.keySet()){
                String str = String.format("%s\001%s", k, value.get(k));
                text.set(str);
                context.write(text, one);
            }
        }
    }

    public static class JsonWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for(IntWritable iw:values){
                count += iw.get();
            }
            context.write(key, new IntWritable(count));
        }
    }

    public static void main(String[] args) throws Exception {
        File out = new File("out");
        if(out.exists()){
            FileUtils.forceDelete(out);
        }

        Configuration conf = new Configuration();
        // 关闭输出压缩
        conf.set("mapreduce.output.fileoutputformat.compress", "false");

        Job job = Job.getInstance(conf, "json word count");
        job.setJarByClass(JsonCount.class);
        job.setMapperClass(JsonWordCountMapper.class);
        job.setReducerClass(JsonWordCountReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        job.setInputFormatClass(JsonInputFormat.class);
        job.setOutputFormatClass(CustomOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
